package com.lxw.nonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxw.nonghe.entity.User;
import com.lxw.nonghe.mapper.PermissionMapper;
import com.lxw.nonghe.mapper.UserMapper;
import com.lxw.nonghe.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Page<User> getUserPage(int current, int size, String username) {
        Page<User> page = new Page<>(current, size);
        return (Page<User>) this.baseMapper.selectUserPage(page, username);
    }

    @Override
    public User getUserByUsername(String username) {
        return this.lambdaQuery().eq(User::getUsername, username).one();
    }

    @Override
    public Page<User> queryUsers(User queryUser, int current, int size) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (queryUser.getUserId() != null) {
            wrapper.eq(User::getUserId, queryUser.getUserId());
        }
        if (queryUser.getUsername() != null && !queryUser.getUsername().isEmpty()) {
            wrapper.eq(User::getUsername, queryUser.getUsername());
        }
        if (queryUser.getRoleId() != null) {
            wrapper.eq(User::getRoleId, queryUser.getRoleId());
        }
        // 添加对parentCode的条件查询
        if (queryUser.getParentCode() != null && !queryUser.getParentCode().isEmpty()) {
            wrapper.eq(User::getParentCode, queryUser.getParentCode());
        }
        Page<User> page = new Page<>(current, size);
        return this.page(page, wrapper);
    }
    @Override
    public boolean removeBatchByIds(List<Integer> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public List<String> getUserPermissions(Integer userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }

    /**
     * 获取用户总数
     * @return
     */
    @Override
    public long getUserCount() {
        return this.count();
    }

    @Override
    public int[] getRegisterTimes() {
        List<Integer> registerCounts = baseMapper.getRegisterTimes();
        int[] result = new int[12];
        for (int i = 0; i < registerCounts.size(); i++) {
            result[i] = registerCounts.get(i);
        }
        return result;
    }
}
